// Copyright 2016-2101 Pica.
package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.UserManagerDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

/**
 * @Description TODO
 * @Author yuefan
 * @Date 2020-11-23 10:17
 */
@Service
public class UserManagerServiceImpl implements UserManagerService {

    @Autowired
    private UserManagerDao userManagerDao;

    @Override
    public PageResult findAll(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userManagerDao.findAll();
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        int i = userManagerDao.search(user.getUsername());
        if (i > 0) {
            throw new RuntimeException(MessageConstant.ADD_USER_FAIL2);
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        user.setPassword(encode);
        userManagerDao.addUser(user);
        Integer id = user.getId();
        for (Integer roleId : roleIds) {
            userManagerDao.addRoles(id,roleId);
        }
    }

    @Override
    public List<Role> findRoles() {
        return userManagerDao.findRoles();
    }

    @Override
    public User findById(Integer userId) {
        return userManagerDao.findById(userId);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return userManagerDao.findRoleIdsByUserId(userId);
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        userManagerDao.deleteById(user.getId());
        userManagerDao.editUser(user);
        Integer id = user.getId();
        for (Integer roleId : roleIds) {
            userManagerDao.addRoles(id,roleId);
        }
    }

    @Override
    public void delete(Integer userId) {
        userManagerDao.deleteById(userId);

        userManagerDao.delete(userId);
    }

    @Override
    public PageResult findByQueryString(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userManagerDao.findByQueryString(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

}
